import 'package:logger/logger.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:io';
import 'package:synchronized/synchronized.dart';
import 'package:flutter/foundation.dart' show kDebugMode;

class AppLogger {
  static late Logger _logger;
  static bool _enableStack = false;

  static Future<void> init({bool enableStack = true}) async {
    _enableStack = enableStack && kDebugMode;
    _logger = Logger(
      printer: _CustomLogPrinter(showStack: _enableStack),
      output: await _CustomFileOutput.create(),
    );
  }

  static void debug(String message, [StackTrace? stack]) => 
    _log(Level.debug, message, stack);

  static void info(String message) => _logger.log(Level.info, message);

  static void error(String message, [StackTrace? stack]) => 
    _log(Level.error, message, stack);

  static void _log(Level level, String message, [StackTrace? stack]) {
    final enhancedMsg = _enableStack && stack != null 
      ? '$message\n${_formatStack(stack)}' 
      : message;
    
    _logger.log(level, enhancedMsg);
  }

  static String _formatStack(StackTrace stack) => 
    'STACKTRACE:${stack.toString().split('\n').take(5).join('\n')}';
}

class _CustomLogPrinter extends LogPrinter {
  final bool showStack;
  static final levelColors = {
    Level.debug: AnsiColor.fg(12),
    Level.info: AnsiColor.fg(14),
    Level.warning: AnsiColor.fg(208),
    Level.error: AnsiColor.fg(196),
  };

  _CustomLogPrinter({this.showStack = false});

  @override
  List<String> log(LogEvent event) {

    return ['${event.message}'];
  }


}

class _CustomFileOutput extends LogOutput {
  final Lock _lock = Lock();
  final Map<String, File> _activeFiles = {};
  static const int _maxSize = 30 * 1024 * 1024; // 30MB
  static const int _maxFilesPerDay = 20;
  late Directory _baseDir;

  _CustomFileOutput._(this._baseDir);

  static Future<_CustomFileOutput> create() async {
    final dir = await _getLogDirectory();
    print('日志保存路径: ${dir.path}'); // 打印日志路径
    return _CustomFileOutput._(dir);
  }

  // static Future<Directory> _getLogDirectory() async {
  //   final externalDir = await getExternalStorageDirectory();
  //   final logDir = Directory('${externalDir?.path}/AppLogs');
  //   if (!await logDir.exists()) await logDir.create(recursive: true);
  //   return logDir;
  // }
  static Future<Directory> _getLogDirectory() async {
    final Directory appDir;
    
    if (Platform.isAndroid) {
      // Android 优先使用应用专属外部存储
      appDir = await getExternalStorageDirectory() ?? await getApplicationSupportDirectory();
    } else {
      // iOS/其他平台使用应用支持目录
      appDir = await getApplicationSupportDirectory();
    }
    
    final logDir = Directory('${appDir.path}/AppLogs');
    if (!await logDir.exists()) await logDir.create(recursive: true);
    return logDir;
  }


  @override
  Future<void> output(OutputEvent event) async {
    await _lock.synchronized(() async {
      final now = DateTime.now();
      final file = await _getCurrentFile(now);
      
      if (await file.length() > _maxSize) {
        await _rotateFile(file, now);
      }
       print('${event.lines.join('\n')}\n'); // 调试写入路径
      await file.writeAsString(
        '${_formatTime(now)} [${event.level.name}] ${event.lines.join('\n')}\n',
        mode: FileMode.append
      );
    });
  }

  Future<File> _getCurrentFile(DateTime time) async {
    final dateKey = _formatDate(time);
    
    if (!_activeFiles.containsKey(dateKey) || 
        !await _activeFiles[dateKey]!.exists()) {
      final newFile = await _findAvailableFile(dateKey);
      await newFile.create();
      _activeFiles[dateKey] = newFile;
    }
    
    return _activeFiles[dateKey]!;
  }
// 修改后的文件获取逻辑
Future<File> _findAvailableFile(String date) async {
  for (int i = 0; i < _maxFilesPerDay; i++) {
    final file = File('${_baseDir.path}/$date${_suffix(i)}.log');
    if (!await file.exists()) {
      await file.create(recursive: true); // 新增文件创建
      return file;
    }
    if (await file.length() < _maxSize) return file;
  }
  throw Exception('Max daily files reached');
}


  Future<void> _rotateFile(File file, DateTime time) async {
    final newPath = '${file.parent.path}/${_formatDate(time)}${_suffix(_getNextSuffix(file))}.log';
    await file.rename(newPath);
  }

  // 辅助格式化方法
  String _formatDate(DateTime t) => 
    '${t.year}${_twoDigits(t.month)}${_twoDigits(t.day)}';
  
  String _formatTime(DateTime t) => 
    '${t.year}-${_twoDigits(t.month)}-${_twoDigits(t.day)} '
    '${_twoDigits(t.hour)}:${_twoDigits(t.minute)}:${_twoDigits(t.second)}.${t.millisecond.toString().padLeft(3, '0')}';

  String _twoDigits(int n) => n.toString().padLeft(2, '0');
  String _suffix(int num) => num > 0 ? '_${num.toString().padLeft(3, '0')}' : '';
  
  int _getNextSuffix(File file) {
    final match = RegExp(r'_(\d+)\.log$').firstMatch(file.path);
    return match != null ? int.parse(match.group(1)!) + 1 : 0;
  }
}